<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Ajax extends CI_Controller {

    public function __construct() {
      parent::__construct();
      $this->load->model('users_mod');
      $this->load->model('images_mod');
      // Load languge helper
      $this->load->helper('language');
      // Set language
      //if( ! $this->session->userdata('lang') ) // UVEK ES (Spanski)
      {
        $this->session->set_userdata('lang','de');
      }
      // Load language file
      $this->lang->load($this->session->userdata('lang'));

      // Load Favorites library
      $this->load->library('modules');
    }
	    
    /**
     *  AJAX login 
     */
    public function login()
    {
        try{          
          $login = $this->input->post('login');
          
          if( true == $this->users_mod->login($login) )
          {
            $response = array(
                        'ind' => 1,
                        'msg' => "",
                        'redirect_url' => base_url() . "profile.htm"
                    );
          }
          else {
             $response = array(
                        'ind' => 0,
                        'msg' => lang('wrong_login_data')
                    );
          }
        }
        catch (Exception $e) {
            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage()
            );
        }
        
        echo json_encode($response);
    }
    
    public function logout()
    {
        $this->users_mod->logout();
        $response = array(
                        'ind' => 1,
                        'msg' => ""
                    );
        echo json_encode($response);
    }
    
    
    public function forgot_password()
    {
        try{
          $email = $this->input->post('email');
          $this->load->helper('email');
          // Ako je upisan mail validan E-mail i ako postoji u bazi
          // Posalji E-mail sa linkom za upis nove lozinke
          if( "" != $email && valid_email($email) && $this->users_mod->forgot_password($email) ) 
          {
            $response = array(
                        'ind' => 1,
                        'msg' => lang('new_password_sent')
                    );
          }
          else
          {
            $response = array(
                        'ind' => 0,
                        'msg' => lang('wrong_email')
                    );
          }
        }
        catch (Exception $e) {
            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage()
            );
        }
        
        echo json_encode($response);
    }
    
    
    public function check_username()
    {
        try{
          $username = $this->input->post('username');
          //echo $username;
          if( true == $this->users_mod->check_username($username) )
            echo "false"; // Postoji username. Nemoze da se registruje
          else
            echo "true"; // Ne postoji upisan username, moze da se registruje
          
        }
        catch (Exception $e) {
//            $response = array(
//                'ind' => 0,
//                'msg' => 'Following errors occured: <br />' . $e->getMessage()
//            );
            echo "false"; // Greska.
        }
        return;
        //echo json_encode($response);
    }
    
    public function check_email()
    {
        try{
          $email = $this->input->post('email');
          $id = $this->input->post('user_id');
          //echo $username;
          if( true == $this->users_mod->check_email($email,$id) )
            echo "false"; // Postoji email. Nemoze da se registruje
          else
            echo "true"; // Ne postoji upisan email, moze da se registruje
          
        }
        catch (Exception $e) {
//            $response = array(
//                'ind' => 0,
//                'msg' => 'Following errors occured: <br />' . $e->getMessage()
//            );
            echo "false"; // Greska.
        }
        return;
    }
    
    public function update_num_online()
    {
        try{          
          $num_online = $this->users_mod->getNumOnline();
          
          $response = array(
                      'ind' => 1,
                      'msg' => "",
                      'num_online' => $num_online
                  );
        }
        catch (Exception $e) {

            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage(),
                'num_online' => 0
            );
        }
        echo json_encode($response);
    }
    
        
    /**
     * F-ja vrsi jQuery upload slike
     * @param int $id - user.id
     */
    public function upload_image($id)
    {
        $this->load->library('file_upload'); // Ukljuci biblioteku
        $ext = array("image/jpeg","image/jpg","image/gif","image/png"); // Ogranici tip datoteka
        
        // BASE Upload path ( /image/$id )
        $upload_path = $this->config->item('image_path').$id;        
        $field_name = "img";
        // Upload slike. Povratna vrednost je array('status'=>0/1, 'msg'=> 'Poruka o gresci', 'file_name'=> '...')
        $response = $this->file_upload->upload_img($upload_path,$field_name,$ext);
              
        
        //$response['field_name'] = $field_name; // id hiden polja gde se upisuje naziv datoteke
        if( $response['status'] == 1 ) // Upload uspesan
        {
            $file = $response['file_name']; // naziv datoteke
            $this->_process_image($id, $file); // Resize / crop image
            $this->images_mod->insertImage($id,$file); // Insert image name into DB
            $data['images'] = $this->images_mod->getUserImages($id,false);            
            $response['html'] = $this->load->view('profile/part/edit_gallery_items',$data,true);
        }

        echo json_encode($response);
    }
    
    private function _process_image($id,$file)
    {
        $this->load->library("image_lib");
        $image_path = $this->config->item('image_path').$id;
        $img_dir = $image_path."/";
        // Putanja + ime slike
        $orig_img = $image_path .'/'. $file;	
		// Saznaj velicinu originalne slike
		$img_size = getimagesize( $orig_img );
        // BIG - velika slika
        // Ako je sirina veca od 1024 onda se vrsi resize
        if( $img_size[0] > 1024 )
          $this->image_lib->image_resize( $image_path, $file, $image_path.'/big/', 1024, 768);
        else           
          copy( $orig_img , $image_path.'/big/'.$file );
        
        // Slika profila (small) (230x...)
        $this->image_lib->image_resize( $image_path, $file, $image_path.'/small/', 230, 0);
        
        // Mala slika (thumb) 100x100 px
        $dest_dir = $img_dir."thumb/";
        $ratio = $img_size[0]/$img_size[1];
        if( $ratio > 1 ) // Landscape
          $this->image_lib->image_resize( $img_dir, $file, $dest_dir,100*$ratio, 100);
        else
          $this->image_lib->image_resize( $img_dir, $file, $dest_dir, 100, 100/$ratio);
        
        $this->image_lib->image_crop($dest_dir, $file, $dest_dir, 100, 100);
    }
    
    
    /**
     * 
     * @param int $id - ID usera (folder name)
     * @param string $name - image name
     */
    public function image($dir=NULL,$id=NULL,$name=NULL)
    {
        if( $dir!="" )
          $img_url = base_url().'images/'.$id.'/'.$dir."/".$name;
        else
          $img_url = base_url().'images/'.$id."/".$name;
        
        $img_path = $this->config->item('image_path').$id."/".$name;
        $img = @fopen($img_url, 'r');
        $info = @getimagesize($img_path);
        $type = $info['mime'];
        //print_r($info);
        
        if ($img)
        {
            header('Content-Type: '.$type);
            fpassthru($img);
        }  
        
    }
    
    
    public function lock_unlock_img()
    {
        try{
          $id = $this->input->post('id');         
          
          if( true == $this->images_mod->lock_unlock_img($id) ) 
          {
            $user_id = $this->images_mod->getUserId($id);
            $data['images'] = $this->images_mod->getUserImages($user_id,false);            
            $html = $this->load->view('profile/part/edit_gallery_items',$data,true);
            $response = array(
                        'ind' => 1,
                        'msg' => "",
                        'html' => $html
                    );
          }
          else
          {
            $response = array(
                        'ind' => 0,
                        'msg' => lang('status_is_not_changed')
                    );
          }
        }
        catch (Exception $e) {
            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage()
            );
        }
        
        echo json_encode($response);
    }
    
    public function delete_img()
    {
        try{
          $id = $this->input->post('id'); // Image id        
          $user_id = $this->images_mod->getUserId($id);
          
          if( true == $this->images_mod->delete_img($id) ) 
          {            
            $data['images'] = $this->images_mod->getUserImages($user_id,false);            
            $html = $this->load->view('profile/part/edit_gallery_items',$data,true);
            $response = array(
                        'ind' => 1,
                        'msg' => "",
                        'html' => $html
                    );
          }
          else
          {
            $response = array(
                        'ind' => 0,
                        'msg' => lang('photo_not_deleted')
                    );
          }
        }
        catch (Exception $e) {
            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage()
            );
        }
        
        echo json_encode($response);
    }
    
    
    public function set_profile_img()
    {
        try{
          $id = $this->input->post('id'); // Image id        
          $user_id = $this->images_mod->getUserId($id);
          
          if( true == $this->images_mod->set_profile_img($id) ) 
          {            
            //$data['images'] = $this->images_mod->getUserImages($user_id,false);            
            //$html = $this->load->view('profile/part/edit_gallery_items',$data,true);
            $main_image = $user_id.'/'.$this->images_mod->getMainImage($user_id);
            
            $response = array(
                        'ind' => 1,
                        'msg' => "",
                        'main_image' => $main_image
                    );
          }
          else
          {
            $response = array(
                        'ind' => 0,
                        'msg' => lang('photo_not_deleted')
                    );
          }
        }
        catch (Exception $e) {
            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage()
            );
        }
        
        echo json_encode($response);
    }
    
    
    public function update_right_part_menu()
    {
        try{
          $html = $this->load->view('modules/right_part_menu',NULL,true);
          $response = array(
                          'ind' => 1,
                          'msg' => "",
                          'html' => $html
                      );
        }
        catch (Exception $e) {
            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage()
            );
        }
        echo json_encode($response);
    }
    
    public function update_spotlight_users()
    {
        try{       
          $data['spotlight_users'] = $this->users_mod->getSpotlightUsers();
          $html = $this->load->view('modules/elastislide_carousel',$data,true);
          
          $response = array(
                      'ind' => 1,
                      'msg' => "",
                      'html' => $html
                  );
                  
        }
        catch (Exception $e) {
            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage()
            );
        }
        
        echo json_encode($response);
    }
    
} // end class
/* End of file ajax.php */
/* Location: ./application/controllers/ajax.php */